package com.aote.rs;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.web.context.ContextLoaderListener;

import com.aote.rs.entity.WxConfig;

/**
 * 获取微信code,openId
 */
public class WxOpenIdRequest {

	static Logger log = Logger.getLogger(WxOpenIdRequest.class);

	public WxOpenIdRequest() {
	}

	/**
	 * 获取微信授权code请求
	 */
	public void codeRequest(HttpServletRequest request,
			HttpServletResponse response) {
		log.debug("weixin-start-getcode");
		System.out.println("weixin-start-getcode");
		String id = request.getSession().getId();
		String state = "";
		if (request.getParameter("state") != null) {
			state = request.getParameter("state");
		}
		WxConfig wxConfig = (WxConfig) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("wxConfig");
		String appId = wxConfig.getAppID();
		String redirectUrl = wxConfig.getREDIRECT_URL();
		
		try {
			redirectUrl = java.net.URLEncoder.encode(redirectUrl, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			String code_uri = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ wxConfig.getAppID()
					+ "&redirect_uri="
					+ redirectUrl
					+ "&response_type=code&scope=snsapi_base&state=" + state;    
			response.sendRedirect(code_uri);
		} catch (Exception e) {
			log.debug("获取微信code出错" + e.getMessage());
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取微信用户唯一标识 openid
	 */
	public void openidRequest(@Context HttpServletRequest request,
			@Context HttpServletResponse response)
			throws UnsupportedEncodingException {
		WxConfig wxConfig = (WxConfig) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("wxConfig");
		String appId = wxConfig.getAppID();
		String redirectUrl = wxConfig.getREDIRECT_URL();
		String secret = wxConfig.getSecret();
		String result = "";
		String state = "";
		if (request.getParameter("state") != null) {
			state = request.getParameter("state");
		}
		
		log.debug("weixin-start-getopendid");
		String code = request.getParameter("code");
		// 如果code为空，说明若用户禁止授权
		//String url = "http://aofengsoft.com/judingwx/index.html?openid="+result; //巨鼎
		String url = "http://www.china-anstar.com/shaoguanwx/fali.html"; // 韶关
		if (code == null) {
			log.debug("未获取授权code,用户禁止授权");
			try {
				response.sendRedirect(url);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet getRequest = new HttpGet(
					"https://api.weixin.qq.com/sns/oauth2/access_token?appid="
							+ appId + "&secret=" + secret + "&code=" + code
							+ "&grant_type=authorization_code");
			HttpResponse httpResponse;
			httpResponse = httpclient.execute(getRequest);
			HttpEntity entity = httpResponse.getEntity();
			String uuid = UUID.randomUUID().toString();
			if (entity != null) {
				String str = EntityUtils.toString(entity, "UTF-8");
				JSONObject obj = new JSONObject(str);
				result = obj.getString("openid");
				System.out.println("result"+result);
			}
//			return result;
			//String url1 = "http://aofengsoft.com/judingwx/index.html?openid="+result;//巨鼎
			//String url2 = "http://aofengsoft.com/judingwx/jiebang.html?openid="+result;// 巨鼎
			String url1 = "http://www.china-anstar.com/shaoguanwx/index.html?openid="+result;//韶关china-anstar.com
			String url2 = "http://www.china-anstar.com/shaoguanwx/meterreadingdetail.html?openid="+result;
			String url3 = "http://www.china-anstar.com/shaoguanwx/jiebang.html?openid="+result;// 韶关
			
			
			
			
			if(state.equals("jf")){
				response.sendRedirect(url1);
			} else if (state.equals("cb")){
				response.sendRedirect(url2);
			} else {
				response.sendRedirect(url3);
			}
			
		} catch (Exception e) {
			log.debug(e.getMessage());
			throw new RuntimeException(e);
		}
	}

}
